﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfMesDemo2.Models;

namespace WpfMesDemo2.Data
{
    public class MesRepository : IDisposable
    {
        private readonly MesDbContext _context;
        private bool _disposed = false;

        public MesRepository()
        {
            _context = new MesDbContext();
        }

        // 获取所有生产订单
        public List<ProductionOrder> GetAllOrders()
        {
            return _context.ProductionOrders
                .Include(o => o.Products)
                .ToList();
        }

        // 获取单个生产订单
        public ProductionOrder GetOrderById(int id)
        {
            return _context.ProductionOrders
                .Include(o => o.Products)
                .FirstOrDefault(o => o.Id == id);
        }

        // 添加或更新生产订单
        public void SaveOrder(ProductionOrder order)
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    if (order.Id == 0)
                    {
                        // 添加新订单
                        _context.ProductionOrders.Add(order);
                    }
                    else
                    {
                        // 更新现有订单
                        var entry = _context.Entry(order);
                        entry.State = EntityState.Modified;

                        // 处理订单产品关系
                        foreach (var product in order.Products)
                        {
                            if (product.Id == 0)
                            {
                                // 添加新产品
                                _context.Products.Add(product);

                                // 添加订单产品关联
                                _context.OrderProducts.Add(new OrderProduct
                                {
                                    OrderId = order.Id,
                                    ProductId = product.Id,
                                    Quantity = product.Quantity,
                                    //UnitPrice = product.Price
                                });
                            }
                            else
                            {
                                // 更新现有产品
                                var productEntry = _context.Entry(product);
                                productEntry.State = EntityState.Modified;
                            }
                        }
                    }

                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw new Exception("Failed to save order", ex);
                }
            }
        }

        // 删除生产订单（软删除）
        public void DeleteOrder(int id)
        {
            var order = _context.ProductionOrders.Find(id);
            if (order != null)
            {
                order.IsDeleted = true;
                _context.SaveChanges();
            }
        }

        // 获取所有产品
        public List<Product> GetAllProducts()
        {
            return _context.Products.ToList();
        }

        // 添加或更新产品
        public void SaveProduct(Product product)
        {
            if (product.Id == 0)
            {
                _context.Products.Add(product);
            }
            else
            {
                _context.Entry(product).State = EntityState.Modified;
            }

            _context.SaveChanges();
        }

        // 实现IDisposable接口
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }

                _disposed = true;
            }
        }
    }
}
